<script setup>
import * as libs from '../lib';
import * as microbitFs from '@microbit/microbit-fs';
import * as DAPjs from 'DAPjs';

async function connectUsb() {
  const device = await libs.getUsbDevices({filters: []});
  console.log(device)
  console.log(device.productName);
  console.log(device.manufacturerName);
}

async function connectMicrobit() {
  const device = await libs.getUsbDevices({ filters: [
      {
        vendorId: 3368,
      }
    ] });
  console.log(device)
  console.log(device.productName);
  console.log(device.manufacturerName);
  await createFs();
}

async function createFs() {
  // https://online-education.codemao.cn/541/microbit-micropython-v2.hex
  // http://127.0.0.1:5500/src/assets/microbit-aaa.hex
  const file = await fetch('http://127.0.0.1:5500/src/assets/microbit-aaa.hex');
  const hexData = await file.text();
  // console.log(hexData);
  var micropythonFs = new microbitFs.MicropythonFsHex([
    { hex: hexData, boardId: microbitFs.microbitBoardId.V2 },
  ]);
  micropythonFs.write('main.py', `from microbit import *
  display.show('hello world'`)
  const fileList = micropythonFs.ls();
  console.log(fileList);
  const universalHexStrWithFs = micropythonFs.getUniversalHex();


  const transport = new DAPjs.WebUSB(device);
  const daplink = new DAPjs.DAPLink(transport);
  daplink.flash(new Uint32Array(universalHexStrWithFs));
  console.log(daplink);
  try {
    await daplink.connect();
  } catch(error) {
    console.error(error.message || error);
  }
}
</script>

<template>
  <button @click="connectUsb">connect</button>
  <button @click="connectMicrobit">connect microbit</button>
</template>

<style scoped>

</style>
